# -*- coding: ISO-8859-1 -*-
#############################################
## (C)opyright by Dirk Holtwick, 2002-2007 ##
## All rights reserved                     ##
#############################################

__reversion__ = "$Revision: 20 $"
__author__    = "$Author: holtwick $"
__date__      = "$Date: 2007-10-09 12:58:24 +0200 (Di, 09 Okt 2007) $"

import types

# import html5lib
from html5lib import treebuilders, serializer, treewalkers, inputstream, HTMLParser, XMLParser

from xml.dom import Node
import xml.dom.minidom

#from xhtml2pdf.config import *
from xhtml2pdf.utils import StringIO
#from xhtml2pdf.tags import *
#from xhtml2pdf.tables import *

#import xhtml2pdf.css.css as css
#import xhtml2pdf.css.cssDOMElementInterface as cssDOMElementInterface

import logging
log = logging.getLogger(__name__)

'''
class AttrContainer(dict):

    def __getattr__(self, name):
        try:
            return dict.__getattr__(self, name)
        except:
            return self[name]

def pisaGetAttributes(c, tag, attributes):
    global TAGS

    attrs = {}
    if attributes:
        for k, v in attributes.items():
            try:
                attrs[str(k)] = str(v) # XXX no Unicode! Reportlab fails with template names
            except:
                attrs[k] = v

    nattrs = {}
    if TAGS.has_key(tag):
        block, adef = TAGS[tag]
        adef["id"] = STRING
        # print block, adef
        for k, v in adef.items():
            nattrs[k] = None
            # print k, v
            # defaults, wenn vorhanden
            if type(v) == types.TupleType:
                if v[1] == MUST:
                    if not attrs.has_key(k):
                        log.warn(c.warning("Attribute '%s' must be set!", k))
                        nattrs[k] = None
                        continue
                nv = attrs.get(k, v[1])
                dfl = v[1]
                v = v[0]
            else:
                nv = attrs.get(k, None)
                dfl = None
            try:
                if nv is not None:

                    if type(v)==types.ListType:
                        nv = nv.strip().lower()
                        if nv not in v:
                            #~ raise PML_EXCEPTION, "attribute '%s' of wrong value, allowed is one of: %s" % (k, repr(v))
                            log.warn(c.warning("Attribute '%s' of wrong value, allowed is one of: %s", k, repr(v)))
                            nv = dfl

                    elif v == BOOL:
                        nv = nv.strip().lower()
                        nv = nv in ("1", "y", "yes", "true", str(k))

                    elif v == SIZE:
                        try:
                            nv = getSize(nv)
                        except:
                            log.warn(c.warning("Attribute '%s' expects a size value", k))

                    elif v == BOX:
                        nv = getBox(nv, c.pageSize)

                    elif v == POS:
                        nv = getPos(nv, c.pageSize)

                    elif v == INT:
                        nv = int(nv)

                    elif v == COLOR:
                        nv = getColor(nv)

                    elif v == FILE:
                        nv = c.getFile(nv)

                    elif v == FONT:
                        nv = c.getFontName(nv)

                    nattrs[k] = nv

            #for k in attrs.keys():
            #    if not nattrs.has_key(k):
            #        c.warning("attribute '%s' for tag <%s> not supported" % (k, tag))

            except Exception, e:
                log.exception(c.error("Tag handling"))

    #else:
    #    c.warning("tag <%s> is not supported" % tag)

    return AttrContainer(nattrs)
'''

def getAttributes(attributes):
    attrs = {}
    if attributes:
        for k, v in attributes.items():
            try:
                attrs[str(k)] = str(v) # XXX no Unicode! Reportlab fails with template names
            except:
                attrs[k] = v
    return attrs

def getDOM(src, xhtml=False, encoding=None):

    " Parse HTML source and return miniDOM "

    if xhtml:
        parser = XHTMLParser(tree=treebuilders.getTreeBuilder("dom"))
    else:
        parser = HTMLParser(tree=treebuilders.getTreeBuilder("dom"))

    if type(src) in types.StringTypes:
        if type(src) is types.UnicodeType:
            encoding = "utf8"
            src = src.encode(encoding)
        src = StringIO.StringIO(src)

    # Test for the restrictions of html5lib
    if encoding:
        # Workaround for html5lib<0.11.1
        if hasattr(inputstream, "isValidEncoding"):
            if encoding.strip().lower() == "utf8":
                encoding = "utf-8"
            if not inputstream.isValidEncoding(encoding):
                log.error("%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!", encoding)
        else:
            if inputstream.codecName(encoding) is None:
                log.error("%r is not a valid encoding", encoding)

    return parser.parse(
        src,
        encoding=encoding)

if __name__=="__main__":
    TEST = """
    <link href="default.css" rel="stylesheet">
    <style type="text/css">
    b { color: red }
    </style>
    Hello <b>World</b>
    """
    dom = getDOM(TEST)
    print dom.toprettyxml()
